Repository navigation
Add Streamable HTTP transport and per-server headers for MCP servers (part of #185) - #541
rohantiwari9573 wants to merge 3 commits into
Conversation
MCP tool names are chosen by the MCP server and can contain any character, including quotes, backslashes and newlines. Build the generated handler source with repr() literals, so every server and tool name is kept exactly as a string, in the docstring as well as in the values the handler uses. Action names and calls are unchanged. Adds tests with names containing quotes, newlines, triple quotes and a line continuation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… for MCP
Adds the MCP Streamable HTTP transport ("transport": "http", with the
aliases streamable_http and streamable-http): JSON and SSE responses,
Mcp-Session-Id and MCP-Protocol-Version handling, renewing an expired
session once, resuming SSE streams, a size limit per message and
DELETE on close. Redirects are not followed.
Per-server "headers" and "timeout" are validated in mcp_config.json.
${NAME} references in header values resolve only from that server's
own "env", never from the process environment. Header values are
never listed or logged, and URLs are logged without credentials.
Also:
- reload reconnects changed or dead servers and keeps the last good
settings of a server whose new entry is invalid;
- invalid entries are kept on save and reported;
- tool listing is paginated;
- /mcp add --transport http and /mcp header;
- profile bundles validate entries with the same rules and keep local
credentials only for the same server;
- AGENT.md documents the http transport.
The settings payload for the existing editors is unchanged; header
values and stdio arguments are not sent.
Part of CraftOS-dev#185.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zfoong
left a comment
There was a problem hiding this comment.
Thanks for this. On my side all the MCP tests pass (Linux, Python 3.10), including the interop tests against the official mcp 2.3.0 SDK server. A few things I'd like fixed before merging:
1. SSE data is split on Unicode line separators (agent_core/core/impl/mcp/server.py:1353)
stream.aiter_lines() uses httpx's line decoder, which splits like str.splitlines() (U+2028, U+2029, U+0085, \x0b, \x0c, \x1c–\x1e), not only on CR/LF as SSE requires. Both official SDKs write U+2028/U+0085 raw inside data:. A tool result containing one (scraped web text, for example) gets cut in half, the JSON parse fails, and the call ends with "response stream ... ended before the response arrived". Splitting the byte stream on \r\n|\r|\n yourself fixes it. The existing SSETransport (line 590) has the same issue, if you want to fix both.
2. The 16 MB cap doesn't bound memory on SSE (server.py:1380-1399)
The size check runs only after httpx has buffered a whole line, so a data line with no newline is buffered without limit until the deadline. A single 200 MB line peaked at about 830 MB RSS before the "exceeds the 16 MB" error. The byte-level splitter from #1, with a size cap, covers this too.
3. Existing configs become invalid after upgrade (agent_core/core/impl/mcp/config.py:200 and :259)
On dev these entries load and connect (the extra keys are ignored). On this branch they're rejected and the server stops connecting:
{"name": "a", "transport": "stdio", "command": "npx", "args": ["x"], "timeout": 60000}
{"name": "b", "transport": "sse", "url": "https://h/sse", "headers": {"Authorization": "Bearer t"}}Could you validate timeout and headers only for http, or warn and ignore them for the other transports?
4. Bundle import silently drops local credentials (app/ui_layer/settings/profile_bundle.py:841-862)
In replace mode, if a same-named server's command, args or URL differ even slightly (a version pin, a path, a trailing slash), the local entry is replaced with the bundle's blank env and the user's saved tokens are gone, with only a log warning. I agree with the security reasoning, but please either keep the local entry or report it in the import result.
Minor
- Session renewal never clears the old
Mcp-Session-Id(server.py:1068-1075,:1154). If the new initialize response has no session id (for example, the server restarted as stateless), the stale id goes out withnotifications/initialized, gets a 404, and the server stays disconnected until a reload or restart.
…dentials - Split SSE streams on CR, LF and CRLF only. httpx's aiter_lines also splits on U+2028, U+0085 and the other str.splitlines separators, which servers send unescaped inside JSON data. Both the Streamable HTTP transport and the legacy SSE transport use the new splitter. - Enforce the 16 MB limit while a line is being read, so an unterminated line is never held in memory in full. - Accept "headers" and "timeout" on stdio, sse and websocket entries again, as earlier versions did. They are ignored with a one-time warning and kept unchanged in the file. - Profile bundle import keeps a local entry that has saved credentials when the bundle's entry with the same name reaches a different server, and reports the name as skipped. - Clear the old Mcp-Session-Id when a renewed session comes back without one. - Never save over an MCP config file that exists but cannot be read when adding a server; report the error instead. Part of CraftOS-dev#185.
…-settings-ui Brings in the CraftOS-dev#185 review fixes from CraftOS-dev#541.
|
Thanks for the thorough review. All five points are fixed in 61709e2:
Also, adding a server ( Tests: each fix has a regression test that fails on the previous commit. The MCP tests give 220 passed, 8 skipped, and the full suite gives 5095 passed, with only the known |
ahmad-ajmal
left a comment
There was a problem hiding this comment.
Thanks for this, and for the quick turnaround on the first round. I've read all the production changes against dev. Overall this is in good shape: the design is sound and the tests are thorough. There's one fix I'd like before merging, plus some cleanup.
The approach
- Writing the transport directly on
httpxinstead of using the official MCP SDK is the right call for us. The SDK (2.3.0) pulls in server-side packages a client doesn't need (starlette, uvicorn, sse-starlette, pydantic, pyjwt, opentelemetry). Our other transports are hand-written on httpx too. - The security choices are good:
${NAME}only reads the server's ownenv.- Redirects aren't followed.
- Header values are validated and never logged.
- The cost is ~700 lines of protocol code we maintain ourselves. If we add OAuth later, let's look at the SDK again before writing that by hand.
Please fix before merging
- Tool calls can be 1 second slower than they need to be (
_drain, inline comment). - Remove the now-unused
unregister_mcp_tools, and merge the duplicated helpers (inline comments).
OK as follow-ups
- If session renewal fails, the server stays offline until the config changes or the app restarts (inline).
- The web UI doesn't know about invalid entries yet. They look like normal servers, and toggling one shows a "not found" error.
- Header values are hidden from the UI, but
envvalues are still sent to the browser (mcp_list,mcp_get_env). That's where the${NAME}secret actually lives. This was already true before this PR; I assume the UI PR fixes it. - The old SSE transport still can't send headers.
- Not part of this PR:
httpx-sseis inrequirements.txtbut nothing imports it, so we could drop it.
What I tested
On macOS, Python 3.10, with the locked httpx 0.28.1, I ran test_mcp_streamable_http.py, test_mcp_config.py and test_mcp_sse_transport.py: 126 passed. I stubbed out the app's heavy imports so these modules load on their own. I didn't run the lifecycle and settings tests locally.
| chunks.append(chunk) | ||
| return b"".join(chunks) | ||
|
|
||
| async def _drain(self, iterator) -> None: |
There was a problem hiding this comment.
Tool calls can wait an extra second after they already have their answer.
When the server answers as an SSE stream, _drain keeps reading after the response has arrived. It stops when the server closes the stream or when DRAIN_TIMEOUT (1 s) runs out. Servers should close the stream after the response, but the spec doesn't require it. With a server that leaves it open, every tool call waits the full second.
I measured this against a small test server that keeps the stream open: about 1 s per tools/list, against about 1 ms with the change below.
I understand why it's there. If we stop reading halfway, the garbage collector later closes httpx's generator chain from another task, and anyio raises "exit cancel scope in a different task". Closing the iterator ourselves does the same cleanup right away, in this task, without waiting:
async def _drain(self, iterator) -> None:
"""Close an httpx stream iterator now, in this task, so its generator
chain isn't left for the garbage collector to close from another task."""
try:
await iterator.aclose()
except Exception: # noqa: BLE001 — the stream is being discarded
passWith this change the 126 transport, config and SSE tests still pass on httpx 0.28.1 / httpcore 1.0.9, with no event-loop errors or unraisable-exception warnings.
The same applies to _read_limited (line 1285). Once a body is over the limit, it currently keeps downloading it for up to another second just to throw it away. Closing stops that immediately. With this change, _close_stream might be a better name.
| try: | ||
| await self._renew_session(expired) | ||
| except _HTTPTransportError as e: | ||
| self._connected = False |
There was a problem hiding this comment.
If renewing the session fails, the server stays offline until the config changes or the app restarts.
This line marks the connection as closed. After that, MCPClient.call_tool answers "connection lost" for every call to this server, and nothing tries to reconnect. reload() does retry dead servers, but it only runs when mcp_config.json changes. So if the server is briefly unavailable while it restarts, its tools stay broken until someone edits the config or restarts CraftBot.
Two possible fixes:
- have the next call try one reconnect for
httpservers; - or leave
_connectedas it is here, so the next request tries the renewal again.
Fine as a follow-up.
| return f"mcp_{server_name}_{tool_name}" | ||
|
|
||
| @staticmethod | ||
| def unregister_actions(action_names) -> int: |
There was a problem hiding this comment.
unregister_mcp_tools (line 308) is now unused.
This new method replaces it, and nothing calls the old one any more. The old one still has the bug this docstring describes: removing server "foo" also removes "foo_bar"'s tools. Could you delete it so nobody uses it again by mistake?
| return False | ||
|
|
||
|
|
||
| def _missing_config(server: MCPServerConfig) -> List[str]: |
There was a problem hiding this comment.
The same "which env keys are missing?" check is written in several places.
_missing_config here and the env part of _mcp_needs_config in profile_bundle.py (line 152) do the same thing, one on a config object and one on a dict. If they ever drift apart, /mcp list and the bundle importer will report different missing keys for the same server. Could it be one method on MCPServerConfig, for example missing_env_keys()?
The web UI has a third version (MCPSettings.tsx:149). It only looks at env, so it misses keys referenced from headers. In the UI PR it could use needs_config from this payload instead.
| await self._drain(chunks) | ||
| return outcome | ||
|
|
||
| async def _sse_messages(self, lines, outcome: "_StreamOutcome"): |
There was a problem hiding this comment.
There are now two SSE parsers.
This parses SSE events, and SSETransport has its own parser for the same format (around line 591). They already share the line splitter, _sse_lines. Could they share the event parsing too, for example one generator that yields event, data, id and retry?
The line-separator bug from the first round was in both copies, so one shared parser means a fix only has to happen once.
| return MCPConfig() | ||
|
|
||
|
|
||
| def _load_for_update() -> Tuple[Optional[MCPConfig], str]: |
There was a problem hiding this comment.
When the config file is broken, most commands give a misleading error.
Only adding a server uses this loader. Remove, enable, disable, env and header still use load_mcp_config(), which returns an empty config when the file can't be read. They don't damage anything, since they stop when the server isn't found. But the user sees "Server 'x' not found" when the real problem is that the file is broken. Could all the commands that change the file use this loader?
Depends on #540 (this branch is stacked on it; review the top commit only until #540 is merged).
Part of #185.
Summary
This adds the MCP Streamable HTTP transport (
"transport": "http") with per-server HTTP headers and a per-server request timeout. It covers configuration inmcp_config.json, the/mcpcommand, profile bundles and AGENT.md.The transport is written directly on
httpx, which is already a dependency. No new dependencies are added. It is tested against the official MCP Python SDK server (see Testing).Streamable HTTP behaviour (spec 2025-03-26 … 2025-11-25)
Accept: application/json, text/event-stream. Both plain JSON and SSE-stream responses are handled. Notifications expect202 Accepted.2025-11-25, and accepts2025-03-26,2025-06-18or2025-11-25from the server. Anything else fails the connection with a clear error. The negotiated version is sent asMCP-Protocol-Versionon later requests.Mcp-Session-Idreturned byinitializeis sent on every later request.GET+Last-Event-ID. This happens at most 2 times, within the request's deadline, and honours the server'sretry.pingis answered; any other request gets-32601.DELETEwith the session id (5 s limit), then closes the client.nextCursorfor up to 50 pages.Configuration
{ "mcp_servers": [ { "name": "stitch", "description": "Remote MCP server over Streamable HTTP", "transport": "http", "url": "https://example.com/mcp", "headers": { "X-Api-Key": "${STITCH_API_KEY}" }, "env": { "STITCH_API_KEY": "" }, "timeout": 30, "enabled": true } ] }streamable_httpandstreamable-httpare accepted as aliases and saved ashttp.url: must behttp://orhttps://, with a host. User info (user:pass@), fragments and spaces are rejected.headers:Accept,Content-Type,Host,Mcp-Session-Id,MCP-Protocol-Version,Last-Event-IDand the hop-by-hop headers).timeout: seconds per request,0 < timeout ≤ 300, default 30. A tool handler waitstimeout + 10seconds, minimum 60, so the transport's own timeout fires first.${NAME}resolution rule${NAME}in a header value is read only from that server's ownenv, never from the process environment. A missing or empty value fails that server with "set NAME in this server's env" rather than sending an empty credential. This means a config entry written by the agent, or one imported in a profile bundle, cannot pull arbitrary environment variables (other servers' keys, cloud credentials) into a request to its own URL.Lifecycle and reload
reload():/mcp, settings and profile bundles/mcp add <name> --transport http <url> [--timeout N]/mcp header <name> <Header> <value>and/mcp header <name> <Header> --remove/mcp listshows the transport, env keys that still need a value, and invalid entries./mcp add <name> --transport stdio -- python server.pynow splits the command from its arguments.mcp_config.json;${NAME}templates are kept;httptransport, headers, timeout and/mcp header.Testing
All runs are on Windows 11, Python 3.10 unless noted, from a clean checkout of this branch.
test_mcp_config.pytest_mcp_streamable_http.py(local mock server)test_mcp_client_lifecycle.pytest_mcp_settings.pytest_mcp_adapter_names.py(from #540)test_mcp_streamable_http_interop.pyagainst the officialmcp2.3.0 SDK server: connect, list and call in JSON and SSE modes, stateful and stateless (4); a wrong API key is refused (1); the SDK is really present (1)tests/test_mcp*.py, with interop enabledpytest --continue-on-collection-errors --assert=plain, 9 min 36 s)devwithout this change (see below)dev)CRAFTBOT_MCP_INTEROP_PYTHONat an interpreter that hasmcp2.x installed. It is skipped otherwise.agent_core.core.impl.action.managerbefore pytest, as the app does at startup. Without that, the existingnest_asyncioissue on 3.14 also makesdev's own SSE tests fail.--assert=plain: used for the full-suite runs. In a CRLF checkout, pytest's detailed assertion diff for the known AGENT.md failure takes many minutes; plain asserts run every test unchanged and skip only that diff.dev:test_agent_md_copies_identical_and_mention_mini_browser;test_process_ledgerport tests ("listener … never came up");test_web_search_cse_base_url.py(missinggoogleapiclient).Limits and behaviour changes
${NAME}no longer falls back to the process environment. This applies tohttpheaders, which are new, so no existing config relies on it.GETlistener for unsolicited server messages. Headers cover API-key and bearer-token servers.agent_file_system/AGENT.md. The template copy carries the new docs.Size
The diff is +4024/−236 across 18 files. About 2,280 lines are new tests, and about 1,740 are production code and docs. I kept it as one PR because the transport, the config validation and the reload logic share the same header and env rules. If it's easier to review, I can split it into:
/mcp, settings and bundles.